package com.code.common.handler;

import cn.hutool.core.lang.Validator;
import com.code.common.exception.ServiceException;
import com.code.common.model.ErrorCode;
import com.code.common.model.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * Created by IntelliJ IDEA.
 *
 * @author: Yan
 * @date: 2023/03/29
 *
 * 全局异常处理类
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * JSR303 校验参数异常
     * @param e
     * @return
     */
    @ExceptionHandler({MethodArgumentNotValidException.class})
    public ResultVO handleMethodArgumentNotValidException(MethodArgumentNotValidException e){
        BindingResult bindingResult = e.getBindingResult();
        String errorMsg = bindingResult.getFieldError().getDefaultMessage();
        log.error("参数校验失败：{}", errorMsg);
        return ResultVO.ERROR().setMessage(errorMsg);
    }

    /**
     * 自定义统一异常
     * @param e
     * @return
     */
    @ExceptionHandler(ServiceException.class)
    public ResultVO handleCustomException(ServiceException e){
        log.error("ServiceException异常原因：{}", e.getMessage());
        e.printStackTrace();
        if (Validator.isNotEmpty(e.getResponseCode())) {
            ErrorCode errorCode = e.getResponseCode();
            return ResultVO.builder().code(errorCode.getCode()).message(errorCode.getMsg()).data(e.getObject()).build();
        }
        return ResultVO.ERROR().setMessage(e.getMessage()).setData(e.getObject());
    }

    @ExceptionHandler(Exception.class)
    public ResultVO handleException(Exception e){
        log.error("Exception异常原因：{}", e.getMessage());
        e.printStackTrace();
        return ResultVO.ERROR().setMessage(e.getMessage());
    }

}
